package parse;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class PrintDOMParse {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(PrintDOMParse.class.getClassLoader().getResourceAsStream("students.xml"));
            Element root = document.getDocumentElement();
            print(root);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }

    public static void print(Element root){
        // 打印开始标签
        System.out.print("<"+root.getTagName());
        // 打印属性
        NamedNodeMap attributes = root.getAttributes();
        for(int i = 0; i < attributes.getLength();i++){
            System.out.print(" "+attributes.item(i));
        }

        System.out.print(">");

        // 打印标签体
        NodeList childNodes = root.getChildNodes();
        for(int i = 0; i < childNodes.getLength(); i++){
            Node node = childNodes.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE){
                // 如果是元素节点,递归操作
                Element ele = (Element) node;
                print(ele);
            }
            if(node.getNodeType() == Node.TEXT_NODE){
                // 如果是文本节点,直接打印
                System.out.print(node.getTextContent());
            }
        }

        // 打印结束标签
        System.out.print("</"+root.getTagName()+">");
    }

}
